// krigingWorker.js
// eslint-disable-next-line no-undef
importScripts('../../js/libs/d3-contour.v4.min.js', '../../js/libs/kcgis-kriging-plugin.min.js', '../../js/libs/turf.min.js');

self.onmessage = function (e) {
  const {taskType, data} = e.data;
  switch (taskType) {
    case 'kriging':
      handleKrigingTask(data);
      break;
    // 可以添加更多的任务类型
    default:
      console.error('Unknown task type:', taskType);
  }
};

function handleKrigingTask({dataset, legendInfo, hnJson}) {
  const levels = _sortColorValues(legendInfo.label.legendInfo);
  console.log(">>>>>>>>开始进行插值分析");
  const startTime = Date.now(); // 记录开始时间
  // eslint-disable-next-line no-undef
  let krigingContours = kcgis.kriging_contour(dataset, 'level', {
    model: 'exponential', sigma2: 0, alpha: 100,
  }, levels);

  const endTime = Date.now(); // 记录结束时间
  const duration = endTime - startTime; // 计算时长
  console.log(">>>>>>>>插值分析完成耗时：" + duration + " 毫秒");
  let resFeatureCollection = [];
  if (hnJson) {
    console.log(">>>>>>>>开始插值结果裁剪");
    const krigingContoursNew = _splitMultiPolygonOrLargeCoordinates(krigingContours);
    const krigingContoursNew2 = _filterFeaturesByMaxLevel(krigingContoursNew);
    //eslint-disable-next-line no-undef
    const poly2 = turf.polygon(hnJson.features[0].geometry.coordinates[0]);
    // 处理 krigingContoursNew2 中的每个 Feature，计算与 poly2 的交集
    const intersectedFeatures = krigingContoursNew2.features.map(feature => {
      // 计算与 poly2 的交集
      // eslint-disable-next-line no-undef
      const intersection = turf.intersect(turf.featureCollection([feature, poly2]));
      if (intersection) {
        // 赋值 properties 并返回交集 Feature
        intersection.properties = feature.properties;
        return intersection;
      }
      return null;
    }).filter(feature => feature !== null); // 过滤掉 null 结果
    // eslint-disable-next-line no-undef
    const intersectedFeatureCollection = turf.featureCollection(intersectedFeatures);
    resFeatureCollection = _splitMultiPolygonOrLargeCoordinates(intersectedFeatureCollection);
  }
  console.log(">>>>>>>>结果裁剪完成");
  self.postMessage({
    taskType: 'kriging', result: {k: resFeatureCollection, l: legendInfo}
  });
}

// eslint-disable-next-line no-unused-vars
function _sortColorValues(data) {
  const defValue = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
  if (!data || data.length === 0) {
    return defValue; // 默认值
  }
  let values = [];
  data.forEach(item => {
    const ranges = item.text.split('-').map(Number);
    values.push(...ranges);
  });
  values = Array.from(new Set(values)).sort((a, b) => a - b);
  // 如果 values 为空数组，返回默认值
  return values.length === 0 ? defValue : values;
}

function _splitMultiPolygonOrLargeCoordinates(featureCollection) {
  const newFeatures = [];
  featureCollection.features.forEach(feature => {
    if (feature.geometry.type === 'MultiPolygon') {
      feature.geometry.coordinates.forEach(coords => {
        // 创建一个新的 Polygon Feature
        newFeatures.push({
          type: 'Feature', geometry: {
            type: 'Polygon', coordinates: coords
          }, properties: feature.properties
        });
      });
    } else if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates.length >= 2) {
      feature.geometry.coordinates.forEach(coords => {
        // 创建一个新的 Polygon Feature
        newFeatures.push({
          type: 'Feature', geometry: {
            type: 'Polygon', coordinates: [coords]
          }, properties: feature.properties
        });
      });
    } else {
      // 直接添加非 MultiPolygon 且坐标长度小于 2 的 Feature
      newFeatures.push(feature);
    }
  });
  return {
    type: 'FeatureCollection', features: newFeatures
  };
}

function _filterFeaturesByMaxLevel(featureCollection) {
  // 创建一个 Map 来存储每个 coordinates[0] 长度对应的最大 feature
  const lengthMap = new Map();
  featureCollection.features.forEach(feature => {
    // 确保 feature 的类型是 polygon
    if (feature.geometry.type === 'Polygon') {
      // 获取 coordinates[0] 的长度
      const coordinates0Length = feature.geometry.coordinates[0].length;
      // 获取 level 属性
      const level = feature.properties.level;
      // 如果 Map 中没有该长度或当前 feature 的 level 更大，则更新 Map
      if (!lengthMap.has(coordinates0Length) || level > lengthMap.get(coordinates0Length).properties.level) {
        lengthMap.set(coordinates0Length, feature);
      }
    }
  });
  // 重新构建新的 FeatureCollection 对象
  return {
    type: "FeatureCollection", features: Array.from(lengthMap.values())
  };
}
